package com.tusuo.stds.ui.avatar;

import android.app.ProgressDialog;
import android.content.Context;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.ApiResult;
import com.tusuo.stds.rest.UploadResponse;
import com.tusuo.stds.util.Utils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;
import timber.log.Timber;

/**
 * @author J.Huang
 * @version 1.0
 *
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(AvatarPresenter.class)
class AvatarPresenter extends MvpBasePresenter<AvatarView> {

    @Inject
    ApiHelper mApiHelper;

    private Context mContext;
    private String mErrMsgServer;

    private Subscriber<UploadResponse> mUploadImgSubscriber = null;
    private Subscriber<ApiResult> mSetAvatarSubscriber = null;

    AvatarPresenter(Context context) {
        mContext = context;
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);

        Injector.initAvatarPresenterComponent().inject(this);
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mUploadImgSubscriber != null) {
            mUploadImgSubscriber.unsubscribe();
            mUploadImgSubscriber = null;
        }
        if (mSetAvatarSubscriber != null) {
            mSetAvatarSubscriber.unsubscribe();
            mSetAvatarSubscriber = null;
        }
        super.detachView(retainInstance);
    }

    /**
     * 处理图片选取结果
     *
     * @param
     */
    void handleImageSelectResult(String  fileName, ProgressDialog uploadImgProgressDlg) {

        File file = new File(fileName);
        if (!file.exists()) {
            return;
        }

        if (uploadImgProgressDlg == null) {
            uploadImgProgressDlg = new ProgressDialog(mContext);
            uploadImgProgressDlg.setMessage("图片上传中…");
            uploadImgProgressDlg.setCancelable(false);
            uploadImgProgressDlg.setCanceledOnTouchOutside(false);
        }

        uploadImgProgressDlg.show();

        RequestBody requestBody =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);

        Map<String, RequestBody> maps = new HashMap<>();
        maps.put("file\"; filename=\"avatar.jpg\"",requestBody);

        mUploadImgSubscriber = new UploadImgSubscriber(uploadImgProgressDlg);
        mApiHelper.uploadImg(mUploadImgSubscriber, "avatar.jpg", maps,"App_UserImage");
    }

    private class UploadImgSubscriber extends Subscriber<UploadResponse> {

        ProgressDialog mUploadImgProgressDlg;

        public UploadImgSubscriber(ProgressDialog progressDlg) {
            mUploadImgProgressDlg = progressDlg;
        }

        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            if (mUploadImgProgressDlg != null) {
                mUploadImgProgressDlg.dismiss();
            }
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(UploadResponse result) {
            if (result.checkState(mContext)) {
                if (mUploadImgProgressDlg != null) {
                    mUploadImgProgressDlg.dismiss();
                }

                if (result.Total <= 0) {
                    Utils.UI.showToastShort(mErrMsgServer);
                } else {
                    mSetAvatarSubscriber = new SetAvatarSubscriber(result.Data.get(0));
                    mApiHelper.setAvatar(mSetAvatarSubscriber, result.Data.get(0));
                }
            }
        }
    }

    private class SetAvatarSubscriber extends Subscriber<ApiResult> {

        private String mImgUrl;

        public SetAvatarSubscriber(String imgUrl) {
            mImgUrl = imgUrl;
        }

        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            Timber.d(e.toString());
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(ApiResult result) {
            if (result.checkState(mContext)) {
                Utils.UI.showToastShort("设置成功");
                if (getView() != null) {
                    getView().loadAvatar(mImgUrl);
                }
            }
        }
    }
}
